<template>
  <view class="orderInformation">
    <view class="orderAddress" v-if="defaultAddress" @click="gotochooseAdd">
      <text class="add_region">{{defaultAddress.zone}}</text>
      <view class="add_detailed">
        <text class="deta_a">{{defaultAddress.street}}</text>
        <image src="../../static/image/goodDetail/to.png" class="deta_b"></image>
      </view>
      <view class="add_user">
        <text class="user_a">{{defaultAddress.contact}}</text>
        <text class="user_b">{{defaultAddress.contactMobile}}</text>
      </view>
    </view>
    <view v-else class="addressChoose" @click="gotochooseAdd">
      <view class="c-a">请选择收货地址</view>
      <view>
        <image src="../../static/image/goodDetail/to.png" class="deta_b"></image>
      </view>
    </view>
    <view class="orderList">
      <view class="list_title">
        <image src="../../static/image/goodDetail/exchange.png" class="title_a"></image>
        <text class="title_b">采购</text>
      </view>
      <view class="list_content">
        <view class="content" v-if="!isCartBy">
          <image :src="goodObj.infoImageUrl" class="content_image"></image>
          <view class="content_right">
            <view class="content_title">
              <text class="tit_title">{{goodObj.name}}</text>
              <view class="tit_price">
                <text class="price_a">¥</text>
                <text class="price_b">{{goodObj.price}}</text>
              </view>
            </view>
            <view class="content_sq">
              <text class="sq_a">{{(goodObj.selRule+'').toString()}}</text>
              <text class="sq_b">共{{goodObj.selGoodsCount}}件</text>
            </view>
          </view>
          <view class="order_note">
            <text class="note_title">订单备注</text>
            <input class="note_input"  placeholder="选填" v-model="remark"/>
          </view>
        </view>
        <view class="content" v-for="(item,index) in cartGoodsData" :key='index' v-else>
          <view v-for="(sonItem,sonIndex) in item.cartVoList" :key="sonIndex">
            <image :src="sonItem.herf" class="content_image"></image>
            <view class="content_right">
              <view class="content_title">
                <text class="tit_title">{{sonItem.productName}}</text>
                <view class="tit_price">
                  <text class="price_a">¥</text>
                  <text class="price_b">{{sonItem.price}}</text>
                </view>
              </view>
              <view class="content_sq">
                <text class="sq_a">{{sonItem.skuStr}}</text>
                <text class="sq_b">共{{sonItem.quantity}}件</text>
              </view>
            </view>
          </view>
          <view class="order_note">
            <text class="note_title">订单备注</text>
            <input class="note_input"  placeholder="选填" v-model="item.remark"/>
          </view>
        </view>
      </view>
      
    </view>
    <view class="orderAmount">
      <view class="amount_total">
        <text class="total_a">订单总额</text>
        <text class="total_b">￥{{fixedTotalMoney | current}}</text>
      </view>
      <view class="amount_freight">
        <text class="total_a">配送费</text>
        <text class="total_b" v-if="postageData.postageFee > 0">
          ￥{{postageData.postageFee | current}}
        </text>
        <text class="total_b" v-else>
          免邮
        </text>
      </view>
      <view class="amount_cash" v-show="postageData.userCashCoupon>0">
        <text class="total_c">当前可用{{postageData.userCashCoupon}}现金券抵现</text>
        <view class="total_d">
          <text class="wel_moneny" v-if="isUseCash">-￥{{postageData.userCashCoupon>(postageData.totalMoney+postageData.postageFee)?postageData.totalMoney+postageData.postageFee:postageData.userCashCoupon}}</text>
          <switch @change="cashChange" class="wel_switch" color='#4CD964' :checked="isUseCash"/>
        </view>
      </view>
    </view>
    <view class="orderSubmit">
      <view class="submit_left">
        <text class="left_a">应付金额：</text>
        <view class="left_b">
          <text>¥</text>
          <text class="b_moeny">{{postageData.totalMoney?afterTotalMoney:totalMoney | current}}</text>
        </view>
      </view>
      <text class="submit_right" @click="submitOrder">提交订单</text>
    </view>
  </view>
</template>

<script>
import { addressDefault, predictOrder, postageByCart, creatOrderBycart, getpostage, creatOrder } from "@/service/purchaseShop/goods.service.js"
import {deleteCart} from "@/service/purchaseShop/goodsCar.service.js"
export default {
  data() {
    return {
      defaultAddress: '',
      isCartBy: false, // 购物车下单还是直接购买
      // token: gettokenStore(),
      postageData: '',
      goodObj: null,
      goodType: 1,
      totalMoney: 0, // 无地址时总金额
      isUseCash: false,
      remark: '',
      cartGoodsData: '',
      supplierIds: [], // 供货商id
      carGoodsNub: null, // 购物车的ids
      cashData: 0, // 是否使用现金券 0：不使用 1：使用
      fixedTotalMoney: 0, //订单总额
      afterTotalMoney: 0 // 计算后的总金额
    }
  },
  onLoad (options) {
    this.isCartBy = options.isCartBy == 1 ? true : false;
  },
  onShow:function() {
    this.reload();
  },
  methods: {
    reload () {
      if (this.isCartBy) { // 购物车的订单
        this.carGoodsNub = uni.getStorageSync('orderCarNub');
        if (this.carGoodsNub) {
          this.getPredictOrder(); //获取购物车预生成订单
        } else {
          uni.reLaunch({ // 订单已提交去订单列表页
            url: '/pages/purchaseShop/orderList?type=-1'
          });
        }
      } else { // 立即购买的订单
        this.goodObj = uni.getStorageSync('detailData');
        if (!this.goodObj) {
          uni.reLaunch({ // 订单已提交去订单列表页
            url: '/pages/purchaseShop/orderList?type=-1'
          });
        } else {
          this.getAddressStatus() // 拿到数据后去获取地址并计算相关金额
        }
      }
    },
    getAddressStatus() {
      this.defaultAddress = uni.getStorageSync('orderAddress');
      if (this.defaultAddress) {
        this.setHanler() // 有默认地址时处理 
      } else {
        this.getDefaultAddress(); // 获取默认地址
      }
    },
    gotochooseAdd () {
      // 去新增地址页
      if (this.isCartBy) {
        uni.navigateTo({
          url: '/pages/user/address?type=' + 1 + '&isCartBy=' + 1
        });
      } else {
        uni.navigateTo({
          url: '/pages/user/address?type=' + 1
        });
      }
      
    },
    getPredictOrder () { // 获取购物车预生成订单
      let params = {
        ids: this.carGoodsNub,
        addressId: this.defaultAddress.id || ''
      }
      predictOrder(params, (res) => {
        if (res.status == 0) {
          res.data[0].map((item) => {
            item['remark'] = '';
          })
          this.cartGoodsData = res.data[0];
          this.getAddressStatus(); // 拿到数据后去获取地址并计算相关金额
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          }); 
        }
      })
    },
    getCarGoodsCost () { // 计算购物车邮费和折扣
      let params = {
        cartIds: this.carGoodsNub,
        addressId: this.defaultAddress.id
      }
      postageByCart(params, (res) => {
        if (res.status == 0) {
          this.postageData = res.data; // 获取邮费与折扣
          this.fixedTotalMoney = res.data.totalMoney;
          this.afterTotalMoney = res.data.totalMoney + res.data.postageFee;
        }
      })
    },
    submitOrder () { // 提交订单
      if (!this.defaultAddress) {
        uni.showToast({
          title: '请选择地址',
          icon: 'none'
        }); 
        return;
      }
      if (this.isCartBy) {
        let remarkList = [];
        let remkNub = 0;
        this.cartGoodsData.map((item) => {
          if(item.remark == '') {
            remkNub++ // 计算备注为空的个数
          }
          remarkList.push(item.remark);
          item.cartVoList.map(son => {
            this.supplierIds.push(son.supplierId); // 获取供应商id
          })
        })
        if (remkNub == this.cartGoodsData.length) {
          remarkList = [];
        }
        this.supplierIds = Array.from(new Set(this.supplierIds));
        let params = {
          remarks: remarkList.length>0?remarkList.join(','):null,
          cartIds: this.carGoodsNub,
          supplierIds: this.supplierIds.join(','),
          addressId: this.defaultAddress.id
        }
        creatOrderBycart(params, (res) => {
          if (res.status == 0) {
            uni.removeStorageSync('orderCarNub')// 删除存储的购物车商品id 
            uni.removeStorageSync('orderAddress')// 删除地址
            this.deleteCartDatas();
            uni.navigateTo({
              url: '/pages/purchaseShop/orderPay?payID=' + res.data.id + '&isCash=' + this.cashData
            });
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            }); 
          }
        })
      } else {
        let params = {
          token: this.token,
          addressId: this.defaultAddress.id,
          productId: this.goodObj.id,
          skuId: this.goodObj.skuId,
          quantity: this.goodObj.selGoodsCount,
          remark: this.remark,
          skuName: this.goodObj.selRule.toString(),
          entrance: '1'
        }
        creatOrder(params, (res) => {
          if (res.status == 0) {
            uni.removeStorageSync('detailData'); // 删除存储的购物车商品id
            uni.removeStorageSync('orderAddress');// 删除地址 
            uni.navigateTo({
              url: '/pages/purchaseShop/orderPay?payID=' + res.data.id + '&isCash=' + this.cashData
            });
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            }); 
          }
        })
      }
    },
    cashChange (e) {
      this.isUseCash = e.target.value;
      this.cashData = this.isUseCash ? 1 : 0;
      this.calcuAmount()
    },
    calcuAmount () {
      // 现金券计算
      if (this.isUseCash) {
        this.afterTotalMoney = Number(this.postageData.totalMoney + this.postageData.postageFee) - Number(this.postageData.userCashCoupon)
      } else {
        this.afterTotalMoney = Number(this.postageData.totalMoney) + Number(this.postageData.postageFee)
      }
    },
    getDefaultAddress () {
      addressDefault({}, (res) => {
        if (res.status === 0) {
          this.defaultAddress = res.data;
          this.setHanler() // 地址处理
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      });
    },
    // 获取地址后处理
    setHanler () {
      if (this.defaultAddress) { // 地址存在
        // isCartBy?请求<批量>购物车折扣和邮费:请求<单个>商品折扣和邮费
        this.isCartBy ? this.getCarGoodsCost() : this.getpostage();
      } else {
        if (this.isCartBy) {
          console.log(this.cartGoodsData)
          for (var i of this.cartGoodsData) {            
            this.totalMoney += i.aggregate * 1; // 根据现金券变化的总额
            this.fixedTotalMoney += i.aggregate * 1; // 不变的订单总额
          }
        } else {
          console.log(2)
          this.totalMoney = this.goodObj.selGoodsCount * this.goodObj.price;
          this.fixedTotalMoney = this.goodObj.selGoodsCount * this.goodObj.price;
        }
      }
    },
    getpostage () {
      // 获取单个商品的邮费与折扣
      let params = {
        skuId: this.goodObj.skuId,
        quantity: this.goodObj.selGoodsCount,
        addressId: this.defaultAddress.id,
      }
      getpostage(params, (res) => {
        if (res.status == 0) {
          this.postageData = res.data;
          this.fixedTotalMoney = res.data.totalMoney;
          this.afterTotalMoney = res.data.totalMoney + res.data.postageFee;
        }
      })
    },
    deleteCartDatas () {
      let params = {
        ids: this.carGoodsNub
      }
      deleteCart(params, (res) => {})
    }
  }
}
</script>

<style scoped lang="scss">

.nodatas {
  text-align: center;
  font-size: 18rpx;
  padding-top: 30rpx;
}
.orderInformation{
  padding-top: 24rpx;
  padding-bottom: 144rpx;
  background:rgba(250,250,252,1);
}
.orderAddress{
  width:100%;
  height:208rpx;
  background:rgba(255,255,255,1);
  border-radius:8rpx;
}
.orderAddress .add_region{
  display: inline-block;
  height:36rpx;
  font-size:26rpx;
  margin-left: 30rpx;
  margin-top: 26rpx;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  color:rgba(51,51,51,1);
  line-height:36rpx;
}
.orderAddress .add_detailed{
  margin: 12rpx 42rpx 0 30rpx;
}
.add_detailed .deta_a{
  font-size:36rpx;
  font-family:PingFangSC-Semibold,PingFang SC;
  // font-weight:600;
  color:rgba(51,51,51,1);
}
.deta_b{
  width:24rpx;
  height:24rpx;
  float: right;
  margin-top: 14rpx;
}
.orderAddress .add_user{
  margin-top: 20rpx;
  margin-left: 30rpx;
  height:34rpx;
  font-size:24rpx;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  color:rgba(51,51,51,1);
  line-height:34rpx;
}
.add_user .user_b{
  margin-left: 20rpx;
}
.orderList{
  width: 100%;
  min-height: 396rpx;
  margin-top: 24rpx;
  background:rgba(255,255,255,1);
  border-radius:8rpx;
}
.orderList .list_title{
  padding-top: 32rpx;
  margin-left: 32rpx;
}
.list_title .title_a{
  width:36rpx;
  height:32rpx;
  line-height: 40rpx;
  vertical-align: middle;
}
.list_title .title_b{
  display: inline-block;
  width:56rpx;
  font-size:28rpx;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  color:rgba(51,51,51,1);
  margin-left: 10rpx;
}
.list_content .content{
  margin: 30rpx 10rpx 0 30rpx;
}
.content .content_image{
  width:140rpx;
  height:140rpx;
}
.content_right{
  float: right;
  margin-left: 28rpx;
  width: 540rpx;
}
.content .content_title{
  vertical-align: top;
}
.content_title .tit_title{
  float: left;
  max-width: 340rpx;
  font-size:26rpx;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  color:rgba(51,51,51,1);
  line-height:36rpx;
  display: -webkit-box;
  overflow: hidden;
  text-overflow: ellipsis;
  word-wrap: break-word;
  white-space: normal !important;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
.content_title .tit_price{
  float: right;
  margin-right: 22rpx;
  height:28rpx;
  font-size:20rpx;
  font-family:PingFangSC-Medium,PingFang SC;
  font-weight:500;
  color:rgba(51,51,51,1);
  line-height:28rpx;
  margin-top: 30rpx;
}
.tit_price .price_b{
  height:44rpx;
  font-size:32rpx;
  font-family:PingFangSC-Semibold,PingFang SC;
  font-weight:600;
  color:rgba(51,51,51,1);
  line-height:44rpx;
}
.content_sq{
  display: inline-block;
  margin-top: 16rpx;
  width: 100%;
}
.content_sq .sq_a{
  display: inline-block;
  text-align: center;
  padding: 0 10rpx;
  height:32rpx;
  background:rgba(239,239,239,1);
  border-radius:16rpx;
  font-size:20rpx;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  color:rgba(51,51,51,1);
  line-height:32rpx;
}
.content_sq .sq_b{
  float: right;
  height:28rpx;
  margin-right: 22rpx;
  margin-top: 2rpx;
  font-size:20rpx;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  color:rgba(102,102,102,1);
  line-height:28rpx;
}
.order_note{
  margin-top: 36rpx;
  padding-bottom: 36rpx;
}
.order_note .note_title{
  height:40rpx;
  font-size:28rpx;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  color:rgba(51,51,51,1);
  line-height:72rpx;
  float: left;
}
.order_note .note_input{
  display: inline-block;
  width:534rpx;
  height:72rpx;
  background:rgba(245,245,245,1);
  border-radius:10rpx;
  margin-left: 16rpx;
  padding:0 12rpx;
}
.orderAmount {
  width:100%;
  margin-top: 24rpx;
  padding: 32rpx 0 60rpx 0;
  background:rgba(255,255,255,1);
  border-radius:8px;
}
.amount_freight{
  margin-top: 62rpx;
}
.amount_welfare{
  margin-top: 52rpx;
  overflow: hidden;
}
.total_a{
  height:28rpx;
  font-size:26rpx;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  margin-left: 30rpx;
  color:rgba(51,51,51,1);
  line-height:28rpx;
}
.total_b{
  float: right;
  height:24rpx;
  font-size:30rpx;
  margin-right: 30rpx;
  font-family:PingFangSC-Medium,PingFang SC;
  font-weight:600;
  color:rgba(51,51,51,1);
  line-height:28rpx;
}
.total_z{
  float: right;
  height:24rpx;
  font-size:30rpx;
  font-family:PingFangSC-Medium,PingFang SC;
  font-weight:600;
  color:rgba(51,51,51,1);
  line-height:28rpx;
}
.total_c{
  float: left;
  font-size:26rpx;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  margin-left: 30rpx;
  color:rgba(51,51,51,1);
  line-height:64rpx;
}
.total_d{
  float: right;
  font-size:30rpx;
  margin-right: 30rpx;
  font-family:PingFangSC-Medium,PingFang SC;
  font-weight:600;
  color:rgba(51,51,51,1);
}
.wel_moneny{
  height:24rpx;
  font-size:30rpx;
  font-family:PingFangSC-Medium,PingFang SC;
  font-weight:500;
  color:rgba(255,121,49,1);
  line-height:24rpx;
  margin-right: 14rpx;
}
.amount_cash{
  margin-top: 36rpx;
  overflow: hidden;
}
.orderSubmit{
  position: fixed;
  width: 100%;
  height: 120rpx;
  background:rgba(255,255,255,1);
  left: 0;
  right: 0;
  bottom: 0;
}
.orderSubmit .submit_left{
  display: inline-block;
  margin-left: 30rpx;
  margin-top: 36rpx;
  height: 50rpx;
}
.submit_left .left_a{
  height:34rpx;
  float: left;
  font-size:24rpx;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  color:rgba(51,51,51,1);
  line-height:50rpx;
}
.submit_left .left_b{
  display: inline-block;
  height:50rpx;
  font-size:28rpx;
  font-family:PingFangSC-Medium,PingFang SC;
  font-weight:500;
  color:rgba(205,67,57,1);
  line-height:50rpx;
}
.left_b .b_moeny{
  font-size:36rpx;
}
.orderSubmit .submit_right{
  float: right;
  margin-right: 30rpx;
  width:252rpx;
  height:88rpx;
  background:#434343;
  border-radius:44rpx;
  font-size:28rpx;
  font-family:PingFangSC-Medium,PingFang SC;
  font-weight:500;
  color:#F6DA99;
  line-height:88rpx;
  text-align: center;
  margin-top: 16rpx;
}
input {
  font-size: 28rpx;
  color: #999999;
}

.addressChoose{
   line-height: 100rpx; 
   background: #fff;
   padding: 0 30rpx;
   display: flex;
   justify-content: space-between;
   align-items: center;
   font-weight: bold;
   image{margin-top: 0;}
   .c-a {
     font-size: 28rpx;
     font-weight: normal;
   }
 }
</style>
